package com.lemon.smartsafety.ui.activity.address;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.address.AddrBookVo;
import com.lemon.smartsafety.entity.event.address.AddressRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.AddressBookServices;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.RulesUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/12.
 * 联系人属性
 */
public class ContractPropActivity extends SwipeBackActivity {
    @Bind(R.id.metName)
    MaterialEditText metName;
    @Bind(R.id.metPhone)
    MaterialEditText metPhone;
    @Bind(R.id.metRemark)
    MaterialEditText metRemark;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.icon_contact_address)
    TextView iconContactAddress;
    private AddrBookVo mBookVo;

    @Override
    protected void initTitle() {
        setBarTitle("联系人");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(ContractPropActivity.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_address_contact_prop;
    }

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mBookVo = (AddrBookVo) getIntent().getSerializableExtra(BundleKey.ADDRESS_BOOK_VO);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        if (null == mBookVo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
            return;
        }


    }


    @OnClick({R.id.btn_submit,R.id.icon_contact_address})
    public void submitAction(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if (!validateForm()) {
                    return;
                }
                getConfirmDialog("是否提交？", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            doSubmitAction();
                        }
                    }
                }).show();
                break;
            case R.id.icon_contact_address:
                startContact();
                break;
            default:
                break;
        }

    }

    private boolean validateForm() {
        if (TextUtils.isEmpty(metName.getText().toString().trim())) {
            metName.setError("请填写姓名");
            mHUDUtil.showErrorTip(metName.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metPhone.getText().toString().trim())) {
            metPhone.setError("请填写手机号码");
            mHUDUtil.showErrorTip(metPhone.getError().toString());
            return false;
        }

        if (!RulesUtils.isPhoneNumberValid(metPhone.getText().toString().trim())) {
            metPhone.setError("手机号码格式不正确");
            mHUDUtil.showErrorTip(metPhone.getError().toString());
            return false;
        }

        return true;
    }

    public void doSubmitAction() {
        String bookId = StringUtils.nullValue(mBookVo.getBook_id() + "");
        String user_name = StringUtils.nullValue(metName.getText().toString().trim());
        String phone = StringUtils.nullValue(metPhone.getText().toString().trim());
        String remark = StringUtils.nullValue(metRemark.getText().toString().trim());

        AddressBookServices.init().saveContract(bookId, user_name, phone, remark);
    }

    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_ADDRESS_BOOK_SAVE_CONTACT.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            AddressRefreshEvent refreshEvent = new AddressRefreshEvent();
                            AppService.getBus().post(refreshEvent);
                            callFinish();
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    private void startContact() {

        Uri uri = Uri.parse("content://contacts/people");
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, 0);


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                Log.e(TAG, "name" + contacts[0]);
                Log.e(TAG, "number" + contacts[1]);
                if (!CommonUtil.strIsEmpty(contacts[0]) && !CommonUtil.strIsEmpty(contacts[1])) {
                    metName.setText(contacts[0].replace(" ",""));

                    String strPhone=contacts[1].replace(" ","");
                    if(strPhone.contains("+86")){
                        strPhone=strPhone.replace("+86","");
                    }

                    if(strPhone.substring(0,2).equals("86")&&strPhone.length()>11){
                        strPhone= strPhone.substring(2,strPhone.length());
                    }
                     LogUtils.LOGE("strPhone:",strPhone);


                    metPhone.setText(strPhone);
                }


        }
    }


    /**
     * 获取本地联系人
     *
     * @param uri
     * @return
     */
    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


/*    *//*
 * 读取联系人的信息
 *//*
    public void testReadAllContacts() {
        Cursor cursor = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        int contactIdIndex = 0;
        int nameIndex = 0;

        if (cursor.getCount() > 0) {
            contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        }
        while (cursor.moveToNext()) {
            String contactId = cursor.getString(contactIdIndex);
            String name = cursor.getString(nameIndex);
            Log.e(TAG, contactId);
            Log.e(TAG, name);

            *//*
             * 查找该联系人的phone信息
             *//*
            Cursor phones = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                    null, null);
            int phoneIndex = 0;
            if (phones.getCount() > 0) {
                phoneIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            }
            while (phones.moveToNext()) {
                String phoneNumber = phones.getString(phoneIndex);
                Log.e(TAG, phoneNumber);
            }

            *//*
             * 查找该联系人的email信息
             *//*
            Cursor emails = this.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactId,
                    null, null);
            int emailIndex = 0;
            if (emails.getCount() > 0) {
                emailIndex = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
            }
            while (emails.moveToNext()) {
                String email = emails.getString(emailIndex);
                Log.e(TAG, email);
            }

        }
    }*/
}
